﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using TaskManager;

namespace TaskManager
{
    public class WorkerCenter
    {
        private List<Worker> Workers = new List<Worker>();

        private Channel<Channel<IJob>> workChannels;
        private Channel<IJob> jobChannels;

        public WorkerCenter(int count)
        {
            workChannels = new Channel<Channel<IJob>>((UInt32)count);
            jobChannels = new Channel<IJob>((UInt32)count);

            for (int i = 0; i < count; i++)
            {
                var worker = new Worker(workChannels);
                worker.Start();
            }
        }

        public void PublishJob(IJob job)
        {
            jobChannels.Push(job);
        }

        public void Start()
        {
            while (true)
            {
                if (!workChannels.Pop(out var wChannel))
                    break;

                if (!jobChannels.Pop(out var job))
                    break;

                if (!wChannel.Push(job))
                    break;
            }
        }

        public void Stop()
        {
            workChannels?.Close();
            foreach (var item in Workers)
            {
                item.Stop();
            }
        }
    }
}
